/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：MapBuffer.java <br>
 * 创建时间：2015-3-16 下午12:26:00 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2.graphics;

import lostland.gmud.exv2.Game;
import lostland.gmud.exv2.GameConstants;
import lostland.gmud.exv2.Gmud;
import lostland.gmud.exv2.MapScreen;
import lostland.gmud.exv2.MapTile;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;


/**
 * 类名：MapBuffer <br>
 * 说明：
 *
 * @author 12548
 */
public class MapBuffer {

	public Bitmap front, back;

//	private volatile boolean buffered = false;

	private static MapBuffer _instance;

	public static MapBuffer getInstance() {

		if(_instance == null) {
			_instance = new MapBuffer();
		}

		return _instance;
	}

	public volatile Thread bufferThread;

	private void waitCurrentBuffer(){
		if(bufferThread != null){
			while (true){
				try {
					bufferThread.join();
					break;
				} catch (InterruptedException e) {
					//retry
				}
			}
//			buffered = true;
			bufferThread = null;
		}
	}

	private void drawMapInBitmap(Bitmap bmp, int dx, int dy){
		if(bmp == null) {
			bmp = Bitmap.createBitmap((getScreenWidth()), (getScreenHeight()), Config.ARGB_8888);
		}
		bmp.eraseColor(Gmud.getBgColor());
		Canvas canvas = new Canvas(bmp);
		MapScreen.getInstance().getMap().drawWalkingInCanvas(MapTile.getInstance(), MapScreen.X, MapScreen.Y, dx, dy, canvas);
	}

	public void bufferMap(final int dx, final int dy){
		waitCurrentBuffer();

		bufferThread = new Thread(new Runnable() {
			@Override
			public void run() {
				back = Bitmap.createBitmap((getScreenWidth()), (getScreenHeight()), Config.ARGB_8888);
				drawMapInBitmap(back, dx, dy);

//				Logger.i("buffered !");
			}
		});

		bufferThread.setName("BufferThread");
		bufferThread.start();
	}

	public Bitmap getBufferedMap(){
		waitCurrentBuffer();
		if(back != null){
//			Bitmap t = front;
			front = back;
			back = null;
//			buffered = false;
		}

		if(front == null){
			drawMapInBitmap(front, 0, 0);
		}
		return  front;
	}




//	MapBuffer front;

//	SparseBooleanArray cached = new SparseBooleanArray();

	private int getScreenWidth(){
		return GameConstants.RES_W[Game.resolution_level] * MapTile.TILE_WIDTH;
	}

	private int getScreenHeight(){
		return GameConstants.RES_H[Game.resolution_level] * MapTile.TILE_WIDTH;
	}


	private MapBuffer() {

	}

}
